<template>
    <div class="koi-flex">
        <KoiCard>
            <!-- 搜索条件 -->
            <el-form v-show="showSearch" :inline="true">
                <el-form-item label="一级评论内容" prop="content">
                    <el-input placeholder="请输入一级评论内容" v-model="searchParams.content" clearable style="width: 240px"
                        @keyup.enter.native="handleTreeList"></el-input>
                </el-form-item>
                <el-form-item label="二级评论内容" prop="secondContent">
                    <el-input placeholder="请输入二级评论内容" v-model="searchParams.secondContent" clearable
                        style="width: 240px" @keyup.enter.native="handleTreeList"></el-input>
                </el-form-item>
                <el-form-item label="文章相关" prop="deptStatus">
                    <el-select v-model="searchParams.articleId" filterable placeholder="请选择文章" style="width: 200px"
                        :filter-method="getTag" clearable>
                        <el-option v-for="item in options" :key="item.articleId" :label="item.title"
                            :value="item.articleId" />
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="search" plain v-throttle="handleSearch">搜索</el-button>
                    <el-button type="danger" icon="refresh" plain v-debounce="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>

            <!-- 表格头部按钮 -->
            <el-row :gutter="10">
                <el-col :span="1.5" v-auth="['system:role:delete']">
                    <el-button type="danger" icon="delete" plain @click="handleBatchDelete()"
                        :disabled="multiple">删除</el-button>
                </el-col>
                <el-col :span="1.5" v-auth="['system:role:add']">
                    <el-button type="info" icon="Sort" plain @click="toggleExpandAll()">展开/折叠</el-button>
                </el-col>
                <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleTreeList"></KoiToolbar>
            </el-row>

            <div class="h-20px"></div>
            <!-- 数据表格 -->
            <el-table v-if="refreshTreeTable" v-loading="loading" border :data="tableList"
                @selection-change="handleSelectionChange" :expand-row-keys="expandKey" :default-expand-all="isExpandAll"
                row-key="id" :tree-props="{ children: 'childComment', hasChildren: 'hasChildren' }"
                empty-text="暂时没有数据哟🌻">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="序号" prop="id" width="80px" align="center" type="index"></el-table-column>
                <el-table-column label="昵称" prop="nickName" width="150px" align="left"
                    :show-overflow-tooltip="true"></el-table-column>
                <el-table-column label="用户头像" prop="avatarUrl" width="150px" align="center"
                    :show-overflow-tooltip="true">
                    <template #default="{ row }">
                        <el-avatar :size="50" :src="row.avatarUrl" />
                    </template>
                </el-table-column>
                <el-table-column label="评论内容" prop="content" align="center"></el-table-column>
                <el-table-column label="评论图片预览" prop="content" width="120px" align="center" z-index="999999999">
                    <template #default="{ row }">
                        <el-image v-if="row.contentImg.length > 0" style="width: 100px; height: 100px"
                            :src="row.contentImg[0]" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
                            :preview-src-list="row.contentImg" :preview-teleported="true" show-progress
                            :initial-index="4" fit="cover" />
                        <p v-else>暂无评论图片</p>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="createTime" width="180px" align="center"></el-table-column>
                <el-table-column label="操作" align="center" width="120" fixed="right">
                    <template #default="{ row }">
                        <el-tooltip content="删除🌻" placement="top">
                            <el-button type="danger" icon="Delete" circle plain @click="handleDelete(row)"
                                v-auth="['system:role:delete']"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <div class="h-20px"></div>
            <el-pagination background v-model:current-page="searchParams.page" v-model:page-size="searchParams.pageSize"
                :page-sizes="[5, 10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="handleTreeList" @current-change="handleTreeList" />
        </KoiCard>
    </div>
</template>

<script setup lang="ts" name="deptPage">
import { nextTick, ref, onMounted } from "vue";
// @ts-ignore
import { koiNoticeSuccess, koiNoticeError, koiMsgError, koiMsgWarning, koiMsgBox, koiMsgInfo } from "@/utils/koi.ts";
import { handleTree } from "@/utils/index.ts";
// @ts-ignore
import {
    deleteById,
} from "@/api/system/dept/index.ts";
import debounce from 'lodash/debounce'
import { getArticleByTitleId } from "@/api/system/article";
import { getComment, deleteComment } from "@/api/system/comment";
// 表格加载动画Loading
const loading = ref(false);
// 是否显示搜索表单[默认显示]
const showSearch = ref<boolean>(true); // 默认显示搜索条件
const options = ref()
// 表格数据
const tableList = ref<any>();
const total = ref<number>(0);

// 查询参数
const searchParams = ref({
    page: 1, // 第几页
    pageSize: 10, // 每页显示多少条
    content: "",
    secondContent: "",
    articleId: ""
});

/** 重置搜索参数 */
const resetSearchParams = () => {
    searchParams.value = {
        content: "",
        secondContent: "",
        articleId: "",
        page: 1, // 第几页
        pageSize: 10, // 每页显示多少条
    };
};

/** 搜索 */
const handleSearch = () => {
    console.log("搜索");
    handleTreeList();
};

/** 重置 */
const resetSearch = () => {
    console.log("重置搜索");
    resetSearchParams();
    handleTreeList();
};
/**
 * 防抖函数获取文章
 */
const getTag = debounce(async (e: string) => {
    try {
        const res = await getArticleByTitleId(e);
        if (res.code == 0) {
            options.value = res.data;
        }
    } catch (error) {
        console.error("获取标签失败", error);
    }
}, 500);

/** 树形表格查询 */
const handleTreeList = async () => {
    try {
        tableList.value = []; // 重置表格数据
        loading.value = true;
        const res: any = await getComment(searchParams.value);
        total.value = res.data.total; // 总条数
        tableList.value = handleTree(res.data.records, "userId");
        handleExpandKey(res.data.records);
        loading.value = false;
    } catch (error) {
        console.log(error);
        koiNoticeError("数据查询失败，请刷新重试🌻");
    }
};

/** 数据表格 */
const handleTableData = async () => {
    try {
        const res: any = await getComment(searchParams.value);
        console.log("部门数据表格数据->", res.data.records);
        tableList.value = handleTree(res.data.records, "userId");
        handleExpandKey(res.data.records);
    } catch (error) {
        console.log(error);
        koiNoticeError("数据查询失败，请刷新重试🌻");
    }
};

// 展开数据
const expandKey = ref();

/** 展开节点 */
const handleExpandKey = (data: any) => {
    if (data?.data?.records) {
        const records = data.data.records;
        const keys: string[] = [];
        // 遍历所有父级评论
        records.forEach((parentComment: any) => {
            // 如果存在子评论且不为空，则收集父评论ID
            if (parentComment.childComment?.length > 0) {
                keys.push(String(parentComment.id));
            }
        });
        // 去重并赋值（虽然id应唯一，但保险起见）
        expandKey.value = [...new Set(keys)];
    } else {
        expandKey.value = [];
    }
};
onMounted(() => {
    // 获取表格数据
    handleTreeList();
});

const ids = ref([]); // 选择数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用

/** 是否多选 */
const handleSelectionChange = (selection: any) => {
    // console.log(selection);
    ids.value = selection.map((item: any) => item.id);
    single.value = selection.length != 1; // 单选
    multiple.value = !selection.length; // 多选
};
// 重新渲染表格状态
const refreshTreeTable = ref(true);
// 是否展开[默认折叠]
const isExpandAll = ref(false);

/** 展开/折叠 */
const toggleExpandAll = () => {
    refreshTreeTable.value = false;
    isExpandAll.value = !isExpandAll.value;
    nextTick(() => {
        refreshTreeTable.value = true;
    });
}

/** 删除 */
const handleDelete = (row: any) => {
    const id = row.id;
    if (id == null || id == "") {
        koiMsgWarning("请选择需要删除的数据🌻");
        return;
    }
    koiMsgBox("您确认需要删除评论[" + row.content + "]么？")
        .then(async () => {
            try {
                await deleteComment([id]);
                koiNoticeSuccess("删除成功🌻");
                handleTableData();
            } catch (error) {
                console.log(error);
            }
        })
        .catch(() => {
            koiMsgError("已取消🌻");
        });
};

/** 批量删除 */
const handleBatchDelete = () => {
    if (ids.value.length == 0) {
        koiMsgInfo("请选择需要删除的数据🌻");
        return;
    }
    koiMsgBox("您确认需要进行批量删除么？删除后将无法进行恢复？")
        .then(async () => {
            try {
                await deleteComment(ids.value);
                koiNoticeSuccess("批量删除成功🌻");
                handleTableData();
            } catch (error) {
                console.log(error);
            }
        })
        .catch(() => {
            koiMsgError("已取消🌻");
        });
};
</script>

<style lang="scss" scoped></style>
